package com.test.sort;

import java.util.Arrays;

/**
 * 归并排序
 * 1.递归拆分数组分为左右两个数组依次拆分
 * 2.合并数组，依次比较左右两个数组的大小放到临时数组，如果其中一个数组到头就停止，剩下的全部拷贝到临时数组
 */
public class MergetSort {
    public static void main(String[] args) {
        int arr[] = {10, 14, 19, 8, 4, 5, 7, 1, 3, 6, 2};
        int temp[] = new int[arr.length]; //归并排序需要一个额外空间
        mergeSort(arr, 0, arr.length - 1, temp);
        System.out.println("归并排序后=" + Arrays.toString(arr));
    }

    private static void mergeSort(int[] arr, int left, int right, int temp[]) {
        if (left < right) {
            int mid = (left + right) / 2;
            mergeSort(arr, left, mid, temp);
            mergeSort(arr, mid + 1, right, temp);
            merge(arr, left, right, mid, temp);
        }

    }

    private static void merge(int[] arr, int left, int right, int mid, int temp[]) {
        int t = 0;
        int l = left;
        int r = mid + 1;
        while (l <= mid && r <= right) {
            if (arr[l] <= arr[r]) {
                temp[t] = arr[l];
                l++;
            } else {
                temp[t] = arr[r];
                r++;
            }
            t++;
        }

        while (l <= mid) {
            temp[t] = arr[l];
            l++;
            t++;
        }

        while (r <= right) {
            temp[t] = arr[r];
            r++;
            t++;
        }

        t = 0;
        l = left;
        while (l <= right) {
            arr[l] = temp[t];
            l++;
            t++;
        }
    }
}